import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'

// 导入 相应的组件对象
import Register from '@/views/Register'
import Login from '@/views/Login'
import Layout from '@/views/Layout'
import Home from '@/views/Layout/Home'
import UserInfo from '@/views/Layout/User/UserInfo'

Vue.use(VueRouter)

const routes = [
  {
    path: '/register',
    component: Register
  }, {
    path: '/login',
    component: Login
  }, {
    path: '/',
    component: Layout,
    redirect: '/home', // 重定向
    children: [// 路由嵌套
      {
        path: 'home',
        component: Home
      }, {
        path: 'user-info',
        component: UserInfo
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由的全局前置守卫，所有的路由跳转前都要经过这里
router.beforeEach((to, from, next) => {
  // 1. 获取token
  const { token } = store.state.user
  // 2. 根据有无token，决定是否放行
  if (token) { // 有token，直接放行
    next()
  } else { // 没有token
    if (to.path === '/') { // 要去首页，先去登录
      next('/login')
    } else { // 直接放行
      next()
    }
  }
})

export default router
